package client_core

import (
	"github.com/chicken-team-outside/chicken_transmission/api_messages"
	"github.com/chicken-team-outside/chicken_transmission/proxy_server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"os"
)

func initFsOpApi(group *gin.RouterGroup) {
	group.GET("/list_dir", listDir)
	group.POST("/rename", rename)
	group.POST("/mkdir", mkdir)
	group.POST("/del", remove)
}

type idPathQuery struct {
	Id     uint64 `json:"id" form:"id" binding:"required"`
	Path   string `json:"path" form:"path" binding:"required"`
	Folder bool   `json:"folder" form:"folder"`
}

func listDir(ctx *gin.Context) {
	query := new(idPathQuery)
	if err := ctx.BindQuery(query); err != nil {
		zap.L().Debug("failed to bind query", zap.Error(err))
		BadParameter(ctx)
		return
	}
	dir, err := sfsClient.ListDir(ctx, query.Id, &api_messages.ListFilesQuery{Path: query.Path, Folder: query.Folder})
	if err != nil {
		zap.L().Warn("failed to list directory", zap.Error(err), zap.Any("query", query))
		BadRequest(ctx, err.Error())
		return
	}
	Success(ctx, dir, "成功")
}

type renameQuery struct {
	Id uint64 `json:"id" binding:"required"`
	*api_messages.RenameQuery
}

func rename(ctx *gin.Context) {
	query := new(renameQuery)
	err := ctx.BindJSON(query)
	if err != nil {
		zap.L().Warn("failed to bind rename query", zap.Error(err))
		BadParameter(ctx)
		return
	}
	result, err := sfsClient.Rename(ctx, query.Id, query.Tasks...)
	if err != nil {
		zap.L().Error("failed rename", zap.Error(err), zap.Any("query", query))
		utils.BadRequest(ctx, err.Error())
		return
	}
	Success(ctx, result, "操作成功")
}

func mkdir(ctx *gin.Context) {
	query := new(idPathQuery)
	err := ctx.BindJSON(query)
	if err != nil {
		zap.L().Warn("failed to bind mkdir query", zap.Error(err))
		BadParameter(ctx)
		return
	}
	err = sfsClient.MkdirAll(ctx, query.Id, query.Path, os.ModeDir)
	if err != nil {
		BadRequest(ctx, err.Error())
		return
	}
	Success(ctx, nil, "创建成功")
}

type idPathsQuery struct {
	Id    uint64   `json:"id" binding:"required"`
	Paths []string `json:"paths" binding:"required"`
}

func remove(ctx *gin.Context) {
	query := new(idPathsQuery)
	err := ctx.BindJSON(query)
	if err != nil {
		zap.L().Warn("failed to binding query", zap.Error(err))
		BadParameter(ctx)
		return
	}
	result, err := sfsClient.RemoveAll(ctx, query.Id, query.Paths)
	if err != nil {
		zap.L().Error("failed to remove query", zap.Error(err), zap.Any("query", query))
		BadRequest(ctx, err.Error())
		return
	}
	Success(ctx, result, "删除成功")
}
